import {
	asyncRoutes,
	constantRoutes
} from '@/router'
import Layout from '@/layout'
import CommonInnerLink from '@/views/common/common-inner-link.vue'
	import {
		getToken
	} from '@/utils/auth'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(auths, route) {
	return true
}


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, auths) {
	const res = []

	routes.forEach(route => {
		const tmp = {
			...route
		}
		if (hasPermission(auths, tmp)) {
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, auths)
			}
			res.push(tmp)
		}
	})

	return res
}

const state = {
	routes: [],
	addRoutes: []
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = constantRoutes.concat(routes)
	}
}


const actions = {
	generateRoutes({
		commit
	}, menus) {
		return new Promise(resolve => {
			let accessedRoutes = filterAsyncRoutes(asyncRoutes, menus)
			// 添加动态路由
			accessedRoutes = accessedRoutes.concat(menuToRouter(menus))
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	}
}
/**
 * 菜单转为路由
 * @param {Object}
 */
function menuToRouter(menus) {
	let routerArr = [];
	for (var i = 0; i < menus.length; i++) {
		let currentMenu = getRoute(menus[i]);
		if (menus[i].children.length > 0) {
			currentMenu['children'] = menuToRouter(menus[i].children);
		}
		routerArr.push(currentMenu);
	}
	return routerArr;
}

function getRoute(item) {

	if(item.menuType == "2"){
		if(!item.menuParams){
			item.menuParams ={};
		}else{
			item.menuParams = JSON.parse(item.menuParams);
		}

		item.menuParams["menuUrl"] = item.menuUrl

		let route = {
			// 路由的路径
			path: "/common/link",
			// 路由名
			name: item.menuName,
			component: CommonInnerLink,
			props: { menuParams: JSON.stringify(item.menuParams) },
			meta: {
				id: item.menuId,
				icon: item.menuLogo,
				title: item.menuName,
			},
			// 路由的子路由
			children: []
		}
		return route
	}

	if(item.menuType == "3"){
		item.menuUrl += "?X-Token=" + getToken();
	}

	// 路由基本格式
	let route = {
		// 路由的路径
		path: item.menuUrl ? item.menuUrl : item.menuCode,
		// 路由名
		name: item.menuName,
		// component: (resolve) => require([`@/layout/Index`], resolve),
		component: item.menuUrl ? (resolve) => require([`@/views${item.menuUrl}`], resolve) : Layout,
		meta: {
			id: item.menuId,
			icon: item.menuLogo,
			title: item.menuName,
		},
		// 路由的子路由
		children: []
	}
	// 返回 route
	return route
}


export default {
	namespaced: true,
	state,
	mutations,
	actions
}
